<template>
  <!-- recommend vue prop sort
  is v-for v-if v-else-if v-else v-show v-cloak v-pre v-once id ref key slot v-model all-normal-props v-bind v-on v-html v-text-->
  <div>
    <div class="wallet-banner linear-bg-blue">
      <h1 class="big-amount">{{pensionNum}}</h1>
      <p class="action">
        <span>豆豆总数</span>
        <span class="icon" @click="handleCharge">充值</span>
      </p>
    </div>
    <div class="list">
      <h1 class="tab-title">收支记录</h1>
      <!-- <div class="list-title">
        <span class="col">内容</span>
        <span class="col">变动</span>
        <span class="col">时间</span>
      </div>-->
      <scroll-view
        class="scroll-wrap no-scroll-bar"
        scroll-y
        @scrolltolower="handleLoadMore"
      >
        <div v-for="(item,idx) in list" :key="idx" class="info-block">
          <div class="left">
            <p>{{item.content}}</p>
            <span>{{item.createDate}}</span>
          </div>
          <div class="right">{{item.pension}}</div>
        </div>
        <!-- <div v-for="(item,idx) in list" :key="idx" class="info-block">
          <span class="col ellipsis-2">{{item.content}}</span>
          <span class="col ellipsis-2">{{item.pension}}</span>
          <span class="col ellipsis-2">{{item.createDate}}</span>
        </div>-->
        <p v-if="alreadyLastPage" class="end-tip">没有更多了</p>
      </scroll-view>
    </div>

    <div class="popup-window" :class="{show:showPopup}">
      <span class="close-icon" @click="handleHide">&times;</span>
      <div v-if="!qrURL" key="1" class="popup-wrap">
        <input
          v-model="orderAmount"
          class="input-block"
          type="number"
          placeholder="请输入充值数量"
          placeholder-class="placeholder-part"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="chargePension">确定</span>
        </div>
      </div>
      <div v-else key="2" class="qr-wrap">
        <img :src="qrURL" mode="aspectFit" class="qr-code" />
        <p class="tip">请识别二维码进行支付</p>
        <button class="btn-color-blue" @click="scanPayOrder">我已完成支付</button>
      </div>
    </div>
  </div>
</template>

<script>
import {} from '@/utils'
import {
  FIND_SHOP_BASE_INFO,
  FIND_SHOP_PENSION_LOG_PAGE,
  FIND_CHARGE_ACCOUNT_ORDER,
  CHARGE_PENSION,
  FIND_USER_OPEN_ID
} from '@/api'
import { Base64 } from 'js-base64'

export default {
  components: {},
  props: {},
  data () {
    return {
      pension: '',
      currentPage: 1,
      logList: [],
      alreadyLastPage: false,
      showPopup: false,
      orderAmount: '',
      orderNum: '',
      qrURL: '',
      openId: ''
    }
  },
  computed: {
    account () {
      return this.$store.state.account
    },
    pensionNum () {
      if (this.pension || this.pension === 0) {
        return this.pension
      } else {
        return ''
      }
    },
    list () {
      return this.logList.map(_ => _)
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.getwxCode()
    this.getShopBaseInfo()
    this.getPensionLog()
  },
  methods: {
    handleCharge () {
      // this.showPopup = true // 21091024 改成跳转到新页面充值
      this.$router.push('/pages/mine/pension-pay/main')
    },
    handleLoadMore () {
      if (!this.alreadyLastPage) {
        this.getPensionLog()
      }
    },
    handleHide () {
      const vm = this
      vm.showPopup = false
      setTimeout(() => {
        if (vm.orderNum) {
          vm.getShopBaseInfo()
        }

        vm.orderAmount = ''
        vm.orderNum = ''
        vm.qrURL = ''
      }, 300)
    },

    getShopBaseInfo () {
      const vm = this

      FIND_SHOP_BASE_INFO(vm.account.shopId)
        .then(r => {
          if (r.data.code === '0') {
            vm.pension = r.data.data.pension
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    getPensionLog () {
      const vm = this

      let params = {
        shopId: vm.account.shopId
      }

      FIND_SHOP_PENSION_LOG_PAGE(params, vm.currentPage, 10)
        .then(r => {
          if (r.data.code === '0') {
            let { list, isFirstPage, isLastPage } = r.data.data
            vm.printList(list, isFirstPage, isLastPage)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    printList (list, isFirst, isLast) {
      if (isFirst) {
        this.logList = list
        if (isLast || !list.length) {
          // only one page
          this.alreadyLastPage = true
        } else {
          // has next page
          this.alreadyLastPage = false
          this.currentPage += 1
        }
      } else if (isLast) {
        // more than one page and this is the last page
        this.logList.push(...list)
        this.alreadyLastPage = true
      } else {
        // middle page
        this.logList.push(...list)
        this.alreadyLastPage = false
        this.currentPage += 1
      }
    },
    chargePension () {
      const vm = this

      if (!vm.orderAmount) {
        vm.$toast('请输入充值数量')
        return false
      }

      let params = {
        // amount: vm.orderAmount * 0.01,
        amount: vm.orderAmount,
        providerId: vm.account.providerId,
        relateMan: vm.account.shopId,
        storeIdentityEnum: 'SHOP',
        openId: vm.openId,
        payMerId: vm.$store.state.payMerId,
        payMethodEnum: 'MINI', // 之前是改了的WECHAT
        paySourceEnum: 'H5' // 之前是改了的MINI
      }

      CHARGE_PENSION(params)
        .then(r => {
          if (r.data.code === '0') {
            // vm.qrURL = 'data:image/png;base64,' + r.data.data.data
            // vm.orderNum = r.data.data.orderNum
            if (r.data.data && r.data.data.data) {
              let payInfo = Base64.decode(r.data.data.data)
              vm._callWechatPay(JSON.parse(payInfo))
            }
          } else if (r.data.message === '未找到云账户信息') {
            vm
              .$alert(
                '您暂未开通云账户，请到爱卡卡开店宝pc端管理系统登录开通。详情请咨询400-888-5115'
              )
              .then(r => {
                vm.$router.go(-1)
              })
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {})
    },
    getwxCode () {
      const vm = this
      wx.login({
        timeout: 6000,
        success: function (res) {
          vm._getWxCode(res.code)
        },
        fail: function (err) {
          console.error(err)
        }
      })
    },
    _getWxCode (code) {
      const vm = this
      let appId = vm.$store.state.appId
      let appSecret = Base64.decode(vm.$store.state.appSecret)
      FIND_USER_OPEN_ID(appId, appSecret, code)
        .then(r => {
          if (r.data.code === '0') {
            vm.openId = r.data.data
          } else {
            this.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.info(e)
        })
    },
    _callWechatPay (payInfo) {
      const vm = this

      console.log(payInfo)

      wx.requestPayment({
        ...payInfo,
        success: function (res) {
          vm.$alert('支付成功', '').then(() => {
            vm.$router.go(-1)
          })
        },
        fail: function (err) {
          console.log(err)
          if (err.errMsg === 'requestPayment:fail cancel') {
          } else {
            vm.$toast('支付失败')
          }
        }
      })
    },
    scanPayOrder () {
      const vm = this

      FIND_CHARGE_ACCOUNT_ORDER(vm.orderNum)
        .then(r => {
          if (r.data.code === '0') {
            if (r.data.data && r.data.data.state) {
              // charge success
            } else {
              vm.$toast('支付信息未找到，请稍后再试')
            }
            setTimeout(() => {
              vm.handleHide()
            }, 300)
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';

.list {
  height: calc(100% - 120px + 35px);
  > .tab-title {
    font-size: 15px;
    height: 35px;
    line-height: 35px;
    text-align: center;
  }
  > .list-title {
    height: 35px;
    padding: 0 15px;
    font-size: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid $light-gray;
    > .col {
      color: $gray;
      width: 33%;
      text-align: center;
    }
  }
  > .scroll-wrap {
    height: calc(100% - 70px + 35px);
    box-sizing: border-box;
    padding: 0 15px;
    .info-block {
      font-size: 14px;
      padding: 10px 0;
      // border-bottom: 1px solid $light-gray;
      display: flex;
      justify-content: space-between;
      align-items: center;
      // > .col {
      //   width: 25%;
      //   text-align: center;
      // }
      .left {
        p {
          font-size: 16px;
          color: #000;
          margin-bottom: 3px;
        }
        span {
          font-size: 14px;
          color: #666;
        }
      }
      .right {
        font-size: 13px;
        color: #ffbe0d;
      }
    }
    .end-tip {
      margin: 0;
      padding: 15px;
      text-align: center;
      color: $gray;
      font-size: 15px;
    }
  }
}
.popup-window {
  display: flex;
  justify-content: center;
  align-items: center;
  > .popup-wrap,
  > .qr-wrap {
    background-color: $white;
    width: 280px;
    border-radius: 8px;
    padding: 15px 15px 60px;
    position: relative;
    overflow: hidden;
    > .input-block {
      width: calc(100% - 20px);
      padding: 5px 10px;
      font-size: 15px;
      border: 1px solid $light-gray;
      border-radius: 4px;
    }
    > .popup-btn-wrap {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid $light-gray;
      > .cancel-btn,
      > .confirm-btn {
        width: 50%;
        height: 40px;
        line-height: 40px;
        font-size: 15px;
        text-align: center;
        background-color: $white;
        &.confirm-btn {
          color: $blue;
          border-left: 1px solid $light-gray;
        }
      }
    }
  }
  > .qr-wrap {
    > .qr-code {
      width: 250px;
      height: 250px;
    }
    > .tip {
      font-size: 12px;
      color: $blue;
      text-align: center;
    }
    > .btn-color-blue {
      position: absolute;
      bottom: 20px;
      left: 15px;
      width: calc(100% - 30px);
    }
  }
}
</style>
